package com.yxq.mdt.app.modules.spikeorder.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.base.RespBase;
import com.yxq.mdt.app.modules.adapter.UploadImageListAdapter;
import com.yxq.mdt.app.modules.bean.UploadImageBean;
import com.yxq.mdt.app.modules.order.bean.EventOrderMsg;
import com.yxq.mdt.app.modules.order.bean.UploadImageResultBean;
import com.yxq.mdt.app.modules.spikeorder.bean.OrderCommentBean;
import com.yxq.mdt.app.modules.spikeorder.bean.OrderCommentPreviewBean;
import com.yxq.mdt.app.modules.spikeorder.model.SpikeOrderModel;
import com.yxq.mdt.app.modules.spikeorder.ui.adapter.SpikeOrderCommentListAdapter;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.ImageUploader;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author L
 * @time
 * @describe 订单评价页面
 */
public class SpikeOrderCommentActivity extends BaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    UploadImageListAdapter uploadImageListAdapter;
    SpikeOrderCommentListAdapter orderCommentListAdapter;
    Map<Integer, UploadImageListAdapter> uploadImageListAdapterMap;

    @Override
    public int getLayoutId() {
        return R.layout.activity_order_comment;
    }

    @Override
    public void initView() {
        uploadImageListAdapterMap = new HashMap<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        orderCommentListAdapter = new SpikeOrderCommentListAdapter(R.layout.layout_item_order_comment_layout, null);
        recyclerView.setAdapter(orderCommentListAdapter);
        orderCommentListAdapter.setOrderCommentInterface(new SpikeOrderCommentListAdapter.OrderCommentInterface() {
            @Override
            public void selectImage(int position, UploadImageListAdapter adapter) {
                uploadImageListAdapter = adapter;
                uploadImageListAdapterMap.put(Integer.valueOf(position), adapter);
                selectImages();
            }
        });
    }

    /**
     * 获取需要上传的图片数组
     *
     * @return
     */
    private List<String> getPicList(UploadImageListAdapter adapter) {
        List<UploadImageBean> data = adapter.getData();
        List<String> picList = new ArrayList<>();
        for (UploadImageBean bean : data) {
            if (bean.getItemType() == 0) {
                picList.add(bean.getPath());
            }
        }
        return picList;
    }

    /**
     * 判断是否需要上传评论图片
     */
    private void submit() {
        if (orderCommentListAdapter == null) {
            return;
        }
        showLoadingDialog();
        //评论数据
        List<OrderCommentBean> orderCommentBeanList = new ArrayList<>();
        List<File> fileList = new ArrayList<>();
        List<Integer> imagesList = new ArrayList<>();//记录每个商品评论的图片数目
        for (int j = 0; j < orderCommentListAdapter.getData().size(); j++) {
            OrderCommentBean orderCommentBean = new OrderCommentBean();
            orderCommentBean.setOrder_detail_id(orderCommentListAdapter.getItem(j).getOrder_detail_id());
            orderCommentBean.setGoods_id(orderCommentListAdapter.getItem(j).getGoods_id());
            orderCommentBean.setGoods_pic(orderCommentListAdapter.getItem(j).getGoods_pic());
            orderCommentBean.setScore(orderCommentListAdapter.getItem(j).getScore());
            orderCommentBean.setContent(orderCommentListAdapter.getItem(j).getContent());
            UploadImageListAdapter adapter = uploadImageListAdapterMap.get(Integer.valueOf(j));
            if (adapter != null && adapter.getData() != null) {
                //上传图片
                int count = 0;
                for (int i = 0; i < adapter.getData().size(); i++) {
                    if (adapter.getData().get(i).getItemType() == 0) {
                        count++;
                        Log.e("图片上传", "" + adapter.getData().get(i).getPath());
                        File file = new File(adapter.getData().get(i).getPath());
                        fileList.add(file);
                    }
                }
                imagesList.add(Integer.valueOf(count));
            } else {
                imagesList.add(Integer.valueOf(0));
            }
            orderCommentBeanList.add(orderCommentBean);
        }

        if (fileList.size() > 0) {
            ImageUploader imageUploader = new ImageUploader();
            imageUploader.setImageUploaderInterface(new ImageUploader.ImageUploaderInterface() {
                @Override
                public void onResponse(List<RespBase<UploadImageResultBean>> response) {
                    Log.e("图片上传", "图片上传完成" + response.size());
                    int count = 0;
                    for (int i = 0; i < imagesList.size(); i++) {
                        if (imagesList.get(i) == Integer.valueOf(0)) {

                        } else {
                            int size = imagesList.get(i);
                            List<String> img = new ArrayList<>();
                            for (int k = 0; k < size; k++) {
                                if (response.get(count).getCode() == 0) {
                                    img.add(response.get(count).getData().getUrl());
                                }
                                count++;
                            }
                            orderCommentBeanList.get(i).setUploaded_pic_list(img);

                        }

                    }
                    submit(JSON.toJSONString(orderCommentBeanList));
                }
            });
            imageUploader.uploadImages(fileList);

        } else {
            submit(JSON.toJSONString(orderCommentBeanList));
        }

    }

    /**
     * 提交评论
     *
     * @param goodsList
     */
    private void submit(String goodsList) {
        //提交评论
        SpikeOrderModel.orderComment(getIntent().getStringExtra("orderId"), "mall", goodsList, new ApiModel.CommonCallback<String>() {
            @Override
            public void onSuccess(String s) {
                hideLoadingDialog();
                EventBus.getDefault().post(new EventOrderMsg(3));
                EventBus.getDefault().post(new EventOrderMsg(4));
                ToastUtils.showShort(s);
                finish();
            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showShort(errMsg);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    parseLocalMedia(images);

//                    File file = new File(images.get(0).getPath());
//                    Log.e("图片上传", "file:" + images.get(0).getPath());
//                    upload(file);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }
    }

    /**
     * 填充图片到界面
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {
        if (uploadImageListAdapter.getData().size() == 0) {
            uploadImageListAdapter.getData().add(new UploadImageBean());
        }
        List<UploadImageBean> data = new ArrayList<>();
        UploadImageBean uploadImageBean;
        List<File> fileList = new ArrayList<>();
        for (LocalMedia localMedia : images) {
            uploadImageBean = new UploadImageBean();
            uploadImageBean.setItemType(0);
            uploadImageBean.setPath(localMedia.getCompressPath());
            data.add(uploadImageBean);
            fileList.add(new File(localMedia.getCompressPath()));
        }
        uploadImageListAdapter.getData().addAll(data);
        if (uploadImageListAdapter.getData().size() == 7) {
            uploadImageListAdapter.getData().remove(0);
        }
        uploadImageListAdapter.notifyDataSetChanged();
    }

    /**
     * 打开图片选择器
     */
    private void selectImages() {
        //相册
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(7 - uploadImageListAdapter.getData().size())//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //评论预览数据
        SpikeOrderModel.commentPreview(getIntent().getStringExtra("orderId"), "mall", new ApiModel.CommonCallback<OrderCommentPreviewBean>() {
            @Override
            public void onSuccess(OrderCommentPreviewBean orderCommentPreviewBean) {
                orderCommentListAdapter.setNewData(orderCommentPreviewBean.getGoods_list());
            }

            @Override
            public void onError(String errMsg) {

            }
        });
    }

    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        submit();
    }
}
